package com.suxin.websocket;

import com.suxin.websocket.handler.AbstractHandler;
import com.suxin.websocket.handler.DefaultHandler;
import com.suxin.websocket.pusher.FriendRelationPusher;
import com.suxin.websocket.pusher.HeartbeatPusher;
import com.suxin.websocket.pusher.RewardClearPusher;
import com.suxin.websocket.session.SessionHolder;
import com.suxin.websocket.session.SessionPath;
import com.suxin.websocket.session.SimpleSessionHolder;
import com.suxin.websocket.session.SimpleSessionPath;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

/**
 * @author Tang
 * @classname FriendRelationServer
 * @description [  ]
 * @date 2022/3/24 10:12
 */
@Component
@ServerEndpoint(value = "/friend/{userId}")
public class FriendRelationServer extends AbstractWebSocketServer<String> {

    private static final SimpleSessionHolder SIMPLE_SESSION_HOLDER = new SimpleSessionHolder();

    private SessionPath sessionPath = new SimpleSessionPath("userId");

    @OnOpen
    @Override
    public void onOpen(Session session) {
        super.onOpen(session);
        // 连接时检测没有需要推送给自己的消息
        getFriendRelationPusher().onOpenPush(Integer.valueOf(this.getSessionPath().getKey()));
    }

    @Override
    public SessionHolder getSessionHolder() {
        return SIMPLE_SESSION_HOLDER;
    }

    @Override
    public SessionPath getSessionPath() {
        return sessionPath;
    }

    @Override
    public AbstractHandler getAbstractHandler() {
        return getDefaultHandler();
    }


    public FriendRelationPusher getFriendRelationPusher() {
        return getApplicationContext().getBean(FriendRelationPusher.class);
    }

    public DefaultHandler getDefaultHandler() {
        return getApplicationContext().getBean(DefaultHandler.class);
    }

    @Configuration
    public class FriendRelationConfigPusher {

        @Bean
        FriendRelationPusher friendRelationPusher() {
            FriendRelationPusher friendRelationPusher = new FriendRelationPusher();
            friendRelationPusher.setSessionHolder(FriendRelationServer.SIMPLE_SESSION_HOLDER);
            return friendRelationPusher;
        }

        @Bean
        HeartbeatPusher heartbeatPusher() {
            HeartbeatPusher heartbeatPusher = new HeartbeatPusher();
            heartbeatPusher.setSessionHolder(FriendRelationServer.SIMPLE_SESSION_HOLDER);
            return heartbeatPusher;
        }

        @Bean
        RewardClearPusher rewardClearPusher() {
            RewardClearPusher rewardClearPusher = new RewardClearPusher();
            rewardClearPusher.setSessionHolder(FriendRelationServer.SIMPLE_SESSION_HOLDER);
            return rewardClearPusher;
        }

    }
}